package com.ingenius.sau.server.service;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.appengine.api.datastore.Blob;
import com.ingenius.sau.client.Constants;
import com.ingenius.sau.server.persistence.jdo.JdoBlobFileDAO;

@SuppressWarnings("serial")
public class FileUploadService extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		ServletFileUpload upload = new ServletFileUpload();
		FileItemIterator iterator = null;
		try {
			iterator = upload.getItemIterator(request);
			while (iterator.hasNext()) {
				FileItemStream item = iterator.next();
				InputStream stream = item.openStream();
				if (!item.isFormField()) {
					Blob blob = new Blob(IOUtils.toByteArray(stream));
					String fileName = item.getName();
					BlobFile file = new BlobFile(fileName, blob);
					String key = JdoBlobFileDAO.getInstance().save(file);

					request.getSession().setAttribute(
							Constants.COOKIE_FILE_URL, key);
					request.getSession().setAttribute(
							Constants.COOKIE_FILE_NAME, fileName);
				}

			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}

}
